package com.edu.koudingmusic.services;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.edu.koudingmusic.BaseApplication;
import com.edu.koudingmusic.entities.Mp3Info;
import com.edu.koudingmusic.tools.MediaUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 音乐播放的服务组件
 * 实现功能：
 * 1.播放
 * 2.暂停
 * 3.上一首
 * 4.下一首
 * 5.获取当前的播放进度
 */
public class PlayService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {

    private static final String TAG = "PlayService";
    private MediaPlayer mMediaPlayer;

    // 当前正在播放歌曲的位置
    private int currentPosition;

    private ArrayList<Mp3Info> mMp3Infos;

    private MusicUpdateListener mMusicUpdateListener;

    private boolean isPause = false;

    // 用来切换播放列表
    private int ChangeList = MY_MUSIC_LIST;
    public static final int MY_MUSIC_LIST = 1;
    public static final int MY_LIKE_MUSIC_LIST = 2;
    public static final int MY_PLAY_RECORD_MUSIC_LIST = 2;

    // 播放模式
    public static final int PLAY_ORDER = 1;
    public static final int PLAY_RANDOM = 2;
    public static final int PLAY_SINGLE = 3;
    private int play_Mode = PLAY_ORDER;
    private Random mRandom = new Random();

    // 播放模式
    public int getPlay_Mode() {
        return play_Mode;
    }

    public void setPlay_Mode(int play_Mode) {
        this.play_Mode = play_Mode;
    }


    public int getChangeList() {
        return ChangeList;
    }

    public void setChangeList(int changeList) {
        ChangeList = changeList;
    }

    public void setMp3Infos(ArrayList<Mp3Info> mp3Infos) {
        mMp3Infos = mp3Infos;
    }

    public ArrayList<Mp3Info> getMp3Infos() {
        return mMp3Infos;
    }

    private ExecutorService es = Executors.newSingleThreadExecutor();

    public PlayService() {
    }

    public int getCurrentPosition() {
        return currentPosition;
    }

    public boolean isPause() {
        return isPause;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMp3Infos = MediaUtils.getMp3Infos(this);
        es.execute(updateStatusRunnable);
        BaseApplication application = (BaseApplication) getApplication();
        currentPosition = application.mSharedPreferences.getInt("currentPosition", 0);
        play_Mode = application.mSharedPreferences.getInt("play_Mode", PlayService.PLAY_ORDER);

        Log.e(TAG, "onCreate: currentPosition" + currentPosition + "-----" + play_Mode);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return new PlayController();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (es != null && !es.isShutdown()) {
            es.shutdown();
            es = null;
        }
        mMediaPlayer = null;
        mMp3Infos = null;
        mMusicUpdateListener = null;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {

        switch (play_Mode) {
            case PLAY_ORDER:
                // 顺序播放
                next();
                break;
            case PLAY_RANDOM:
                // 一： 顺序打乱  二：随机
                play(mRandom.nextInt(mMp3Infos.size()));
                break;
            case PLAY_SINGLE:
                play(currentPosition);
                break;
            default:
                break;
        }

    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        mMediaPlayer.reset();
        return false;
    }

    public class PlayController extends Binder {

        public PlayService getPlayService() {
            return PlayService.this;
        }
    }

    // 线程
    private Runnable updateStatusRunnable = new Runnable() {
        @Override
        public void run() {
            while (true) {
                if (mMusicUpdateListener != null && mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                    mMusicUpdateListener.onPublish(getCurrentProgress());
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    };

    // 播放
    public void play(int position) {
        Mp3Info mp3Info = null;
        if (position < 0 || position >= mMp3Infos.size()) {
            position = 0;
        }
        mp3Info = mMp3Infos.get(position);
        try {
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(this, Uri.parse(mp3Info.getUrl()));
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            currentPosition = position;
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (mMusicUpdateListener != null) {
            mMusicUpdateListener.onChange(currentPosition);
        }
    }

    // 暂停
    public void pause() {
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            isPause = true;
        }
    }

    // 下一首
    public void next() {
        if (currentPosition + 1 > mMp3Infos.size()) {
            currentPosition = 0;
        } else {
            currentPosition++;
        }
        play(currentPosition);
    }

    // 上一首
    public void prev() {
        if (currentPosition - 1 < 0) {
            currentPosition = mMp3Infos.size() - 1;
        } else {
            currentPosition--;
        }
        play(currentPosition);
    }

    // 开始播放
    public void start() {
        if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
        }
    }

    public boolean isPlaying() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    // 获取总时长
    public int getDuration() {
        return mMediaPlayer.getDuration();
    }

    // 跳到哪里
    public void seekTo(int mesc) {
        mMediaPlayer.seekTo(mesc);
    }

    // 获取当期那进度
    public int getCurrentProgress() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            return mMediaPlayer.getCurrentPosition();
        }
        return 0;
    }

    // 更新状态的接口
    public interface MusicUpdateListener {
        // 进度条的更新
        public void onPublish(int progress);

        // 更改播放进度
        public void onChange(int position);

    }

    public void setMusicUpdateListener(MusicUpdateListener musicUpdateListener) {
        mMusicUpdateListener = musicUpdateListener;
    }
}
